<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\admin\controller;

use think\Page;
use think\Db;

class Other extends Base
{
    /*
     * 初始化操作
     */
    public function _initialize() 
    {
        parent::_initialize();
        // 判断是否有广告位置
        if (strtolower(ACTION_NAME) != 'index') {
            $count = Db::name('ad_position')->count('id');
            if (empty($count)) {
                $this->success('缺少广告位置，正在前往中……', url('AdPosition/add'), '', 3);
                exit;
            }
        }
    }

    public function index()
    {
        $list = array();
        $get = input('get.');
        $pid = input('param.pid/d', 0);
        $keywords = input('keywords/s');
        $condition = array();
        // 应用搜索条件
        foreach (['keywords', 'pid'] as $key) {
            if (isset($get[$key]) && $get[$key] !== '') {
                if ($key == 'keywords') {
                    $condition['a.title'] = array('LIKE', "%{$get[$key]}%");
                } else {
                    $tmp_key = 'a.'.$key;
                    $condition[$tmp_key] = array('eq', $get[$key]);
                }
            }
        }

        $adM =  Db::name('ad');
        $count = $adM->alias('a')->where($condition)->count();// 查询满足要求的总记录数
        $Page = new Page($count, config('paginate.list_rows'));// 实例化分页类 传入总记录数和每页显示的记录数
        $list = $adM->alias('a')->where($condition)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        /*支持子目录*/
        foreach ($list as $key => $val) {
            $val['litpic'] = handle_subdir_pic($val['litpic']);
            $list[$key] = $val;
        }
        /*--end*/

        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('list',$list);// 赋值数据集
        $this->assign('pager',$Page);// 赋值分页对象

        $ad_position = model('AdPosition')->getAll('*','id');
        $this->assign('ad_position',$ad_position);

        $this->assign('pid',$pid);// 赋值分页对象
        return $this->fetch();
    }
    
    /**
     * 新增
     */
    public function add()
    {
        if (IS_POST) {
            $post = input('post.');
            $is_remote = !empty($post['is_remote']) ? $post['is_remote'] : 0;
            $litpic = '';
            if ($is_remote == 1) {
                $litpic = $post['litpic_remote'];
            } else {
                $litpic = $post['litpic_local'];
            }
            $newData = array(
                'litpic'            => $litpic,
                'admin_id'  => session('admin_id'),
                'sort_order'    => 100,
                'add_time'           => getTime(),
                'update_time'   => getTime(),
            );
            $data = array_merge($post, $newData);
            $insertId = Db::name('ad')->insertGetId($data);

            if ($insertId) {
                \think\Cache::clear('ad');
                adminLog('新增广告：'.$post['title']);
                $this->success("操作成功", url('Other/index'));
            } else {
                $this->error("操作失败");
            }
            exit;
        }

        $pid = input('param.pid/d', 0);
        $this->assign('pid', $pid);

        $ad_position = model('AdPosition')->getAll('*', 'id');
        $this->assign('ad_position', $ad_position);

        $ad_media_type = config('global.ad_media_type');
        $this->assign('ad_media_type', $ad_media_type);

        return $this->fetch();
    }
    
    /**
     * 编辑
     */
    public function edit()
    {
        if (IS_POST) {
            $post = input('post.');
            if(!empty($post['id'])){
                $post['id'] = intval($post['id']);
                $is_remote = !empty($post['is_remote']) ? $post['is_remote'] : 0;
                $litpic = '';
                if ($is_remote == 1) {
                    $litpic = $post['litpic_remote'];
                } else {
                    $litpic = $post['litpic_local'];
                }
                $newData = array(
                    'litpic'            => $litpic,
                    'update_time'       => getTime(),
                );
                $data = array_merge($post, $newData);
                $r = Db::name('ad')->where([
                        'id'    => $post['id'],
                    ])
                    ->cache(true,null,'ad')
                    ->update($data);
            }
            if ($r) {
                adminLog('编辑广告');
                $this->success("操作成功", url('Other/index'));
            } else {
                $this->error("操作失败");
            }
        }

        $assign_data = array();

        $id = input('id/d');
        $field = Db::name('ad')->where([
                'id'    => $id,
            ])->find();
        if (empty($field)) {
            $this->error('广告不存在，请联系管理员！');
            exit;
        }
        if (is_http_url($field['litpic'])) {
            $field['is_remote'] = 1;
            $field['litpic_remote'] = handle_subdir_pic($field['litpic']);
        } else {
            $field['is_remote'] = 0;
            $field['litpic_local'] = handle_subdir_pic($field['litpic']);
        }
        
        /*支持子目录*/
        $field['intro'] = handle_subdir_pic($field['intro'], 'html');
        /*--end*/

        $assign_data['field'] = $field;
        $assign_data['ad_position'] = model('AdPosition')->getAll('*', 'id');

        $assign_data['ad_media_type'] = config('global.ad_media_type');

        $this->assign($assign_data);
        return $this->fetch();
    }
    
    /**
     * 删除
     */
    public function del()
    {
        $id_arr = input('del_id/a');
        $id_arr = eyIntval($id_arr);
        if(!empty($id_arr)){
            $r = Db::name('ad')->where([
                    'id'    => ['IN', $id_arr],
                ])
                ->cache(true,null,'ad')
                ->delete();
            if ($r !== false) {
                adminLog('删除广告-id：'.implode(',', $id_arr));
                $this->success('删除成功');
            }
        }
        $this->error('删除失败');
    }

    /**
     * ui美化新增
     */
    public function ui_add()
    {
        if (IS_POST) {
            $post = input('post.');
            $is_remote = !empty($post['is_remote']) ? $post['is_remote'] : 0;
            $litpic = '';
            if ($is_remote == 1) {
                $litpic = $post['litpic_remote'];
            } else {
                $litpic = $post['litpic_local'];
            }
            $newData = array(
                'media_type'    => 1,
                'litpic'            => $litpic,
                'add_time'       => getTime(),
                'update_time'       => getTime(),
            );
            $data = array_merge($post, $newData);
            $insertId = Db::name('ad')->insertGetId($data);
            if ($insertId) {
                \think\Cache::clear('ad');
                adminLog('新增广告：'.$post['title']);
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }

        $edit_id = input('param.edit_id/d', 0);
        $pid = input('param.pid/d', 0);
        $assign_data = array();
        $assign_data['ad_position'] = model('AdPosition')->getInfo($pid);
        $assign_data['edit_id'] = $edit_id;

        $this->assign($assign_data);
        return $this->fetch();
    }

    /**
     * ui美化编辑
     */
    public function ui_edit()
    {
        if (IS_POST) {
            $post = input('post.');
            if(!empty($post['id'])){
                $post['id'] = intval($post['id']);
                $is_remote = !empty($post['is_remote']) ? $post['is_remote'] : 0;
                $litpic = '';
                if ($is_remote == 1) {
                    $litpic = $post['litpic_remote'];
                } else {
                    $litpic = $post['litpic_local'];
                }
                $newData = array(
                    'litpic'            => $litpic,
                    'update_time'       => getTime(),
                );
                $data = array_merge($post, $newData);
                $r = Db::name('ad')->where([
                        'id'    => $post['id'],
                    ])
                    ->cache(true,null,'ad')
                    ->update($data);
                if ($r) {
                    adminLog('编辑广告：'.$post['title']);
                    $this->success('操作成功');
                }
            }
            $this->error('操作失败');
        }

        $assign_data = array();

        $id = input('id/d');
        $field = Db::name('ad')->where([
                'id'    => $id,
            ])->find();
        if (empty($field)) {
            $this->error('广告不存在，请联系管理员！');
            exit;
        }
        if (is_http_url($field['litpic'])) {
            $field['is_remote'] = 1;
            $field['litpic_remote'] = $field['litpic'];
        } else {
            $field['is_remote'] = 0;
            $field['litpic_local'] = $field['litpic'];
        }
        $assign_data['field'] = $field;
        $assign_data['ad_position'] = model('AdPosition')->getInfo($field['pid']);

        $this->assign($assign_data);
        return $this->fetch();
    }
    
    /**
     * 删除
     */
    public function ui_del()
    {
        $id_arr = input('del_id/a');
        $id_arr = eyIntval($id_arr);
        if(!empty($id_arr)){
            $r = Db::name('ad')->where([
                    'id'    => ['IN', $id_arr],
                ])
                ->cache(true,null,'ad')
                ->delete();
            if ($r) {
                adminLog('删除广告-id：'.implode(',', $id_arr));
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }else{
            $this->error('参数有误');
        }
    }

    /**
     * 移动端的广告配置
     * @return [type] [description]
     */
    public function m_index()
    {
        $advList = Db::name('ad_position')->where(['position'=>3,'status'=>1,'is_del'=>0])->order('id asc')->getAllWithIndex('id');
        $list = Db::name('ad')->alias('a')->field('a.*, b.link_names, b.host_id')
            ->join('ad_link b', 'a.ad_link_id=b.link_id', 'LEFT')
            ->where([
                'a.pid'=>['IN',array_keys($advList)],
                'a.status'=>1,
                'a.is_del'=>0,
            ])
            ->order('a.pid asc, a.sort_order asc, a.id asc')
            ->select();
        $list = get_ad_link_url($list);
        foreach ($list as $key => $val) {
            $advList[$val['pid']]['list'][] = $val;
        }
        $this->assign('advList', $advList);

        return $this->fetch();
    }

    /**
     * 新增移动端广告
     * @return [type] [description]
     */
    public function m_add()
    {
        if (IS_POST) {
            $post = input('post.');
            $post['pid'] = !empty($post['pid']) ? intval($post['pid']) : 0;
            if ($post['pid'] <= 0) {
                $this->error('保存失败');
            }

            if (!empty($post['ad_link_id'])) {
                $post['links'] = '';
            } else if (!empty($post['links'])) {
                $post['ad_link_id'] = 0;
            }

            $post['title'] = trim($post['title']);
            $litpic_list = $post['litpic_list'];
            unset($post['litpic_list']);

            $saveData = [];
            foreach ($litpic_list as $key => $litpic) {
                $addData = [
                    'media_type' => 1,
                    'litpic'            => $litpic,
                    'intro'  =>  '',
                    'admin_id'  => session('admin_id'),
                    'sort_order'    => 100,
                    'add_time'           => getTime(),
                    'update_time'   => getTime(),
                ];
                $addData = array_merge($post, $addData);
                $saveData[] = $addData;
            }
            $rdata = model('Ad')->saveAll($saveData);
            if ($rdata !== false) {
                $ad_ids = [];
                if (3 == $post['ad_host_id']) {
                    $link_names = Db::name('archives')->where(['aid'=>$post['ad_link_id']])->value('title');
                } else if (4 == $post['ad_host_id']) {
                    $link_names = Db::name('arctype')->where(['id'=>$post['ad_link_id']])->value('typename');
                } else {
                    $link_names = Db::name('ad_link')->where(['link_id'=>$post['ad_link_id']])->value('link_names');
                }
                foreach ($rdata as $k1 => $v1) {
                    $id_new = $v1->getData('id');
                    $saveData[$k1]['id'] = $id_new;
                    $saveData[$k1]['link_names'] = !empty($link_names) ? $link_names : '';
                    $ad_ids[] = $id_new;
                }
                \think\Cache::clear('ad');
                adminLog('新增广告：'.implode(',', $ad_ids));
                $this->success("保存成功", url('Other/m_index'), ['list'=>$saveData]);
            }
            $this->error("保存失败");
        }
    }
    
    /**
     * 编辑移动端广告
     */
    public function m_edit()
    {
        if (IS_POST) {
            $post = input('post.');
            $post['ad_id'] = !empty($post['ad_id']) ? intval($post['ad_id']) : 0;
            if ($post['ad_id'] <= 0) {
                $this->error('保存失败');
            }
            isset($post['title']) && $post['title'] = trim($post['title']);

            if (!empty($post['ad_link_id'])) {
                $post['links'] = '';
            } else if (!empty($post['links'])) {
                $post['ad_link_id'] = 0;
            }

            $editData = [
                'admin_id'  => session('admin_id'),
                'update_time'   => getTime(),
            ];
            $editData = array_merge($post, $editData);
            $rdata = Db::name('ad')->where(['id'=>$post['ad_id']])->update($editData);
            if ($rdata !== false) {
                \think\Cache::clear('ad');
                adminLog('编辑广告：'.$post['ad_id']);
                $this->success("保存成功", url('Other/m_index'));
            }
            $this->error("保存失败");
        }
    }

    // 选择广告链接
    public function link()
    {
        $assign_data = [];
        $assign_data['ad_host_id'] = input('param.ad_host_id/d', 1);
        $assign_data['ad_link_id'] = input('param.ad_link_id/d', 0);
        // 链接详情
        $assign_data['linkInfo'] = Db::name('ad_link')->where(['link_id'=>$assign_data['ad_link_id']])->find();
        // 链接分组
        $assign_data['linkGroup'] = Db::name('ad_link')->field('link_id,host_id,host_title')->where(['status'=>1])->group('host_id')->order('host_id asc')->getAllWithIndex('host_id');

        if (3 == $assign_data['ad_host_id']) {
            // 默认查询条件
            $condition = [
                'a.channel' => 2,
                'a.is_del' => 0,
                'a.merchant_id' => 0,
            ];

            // 获取到所有GET参数
            $param = input('param.');

            // 应用搜索条件
            foreach (['keywords'] as $key) {
                $param[$key] = addslashes(trim($param[$key]));
                if (isset($param[$key]) && $param[$key] !== '') {
                    if ($key == 'keywords') {
                        $condition['a.title'] = array('LIKE', "%{$param[$key]}%");
                    } else {
                        $condition['a.'.$key] = array('eq', trim($param[$key]));
                    }
                }
            }

            // 权限控制 by 小虎哥
            $admin_info = session('admin_info');
            if (0 < intval($admin_info['role_id'])) {
                $auth_role_info = $admin_info['auth_role_info'];
                if (!empty($auth_role_info) && isset($auth_role_info['only_oneself']) && 1 == $auth_role_info['only_oneself']) {
                    $condition['a.admin_id'] = $admin_info['admin_id'];
                }
            }

            // 自定义排序
            $orderby = input('param.orderby/s');
            $orderway = input('param.orderway/s');
            if (!empty($orderby) && !empty($orderway)) {
                $orderby = "a.{$orderby} {$orderway}, a.aid desc";
            } else {
                $orderby = "a.aid desc";
            }

            $count = Db::name('archives')->alias("a")->where($condition)->count('a.aid');// 查询满足要求的总记录数
            $Page = $pager = new Page($count, config('paginate.list_rows'));// 实例化分页类 传入总记录数和每页显示的记录数
            $list = Db::name('archives')->alias("a")->field('a.*')->where($condition)->order($orderby)->limit($Page->firstRow.','.$Page->listRows)->select();
            foreach ($list as $key => $val) {
                $val['litpic'] = get_default_pic($val['litpic']);
                $list[$key] = $val;
            }
            $assign_data['param'] = $param;
            $assign_data['page'] = $Page->show();
            $assign_data['list'] = $list;
            $assign_data['pager'] = $Page;
        }
        else if (4 == $assign_data['ad_host_id']) {
            // 目录列表
            $where = [
                'current_channel' => 2,
                'is_del' => 0,
            ];
            $arctypeLogic = new \app\common\logic\ArctypeLogic;
            $assign_data['arctype_list'] = $arctypeLogic->arctype_list(0, 0, false, 0, $where, false);

            // 获取所有有子栏目的栏目id
            $where = [
                'parent_id' => ['gt', 0],
                'is_del' => 0,
            ];
            $parent_ids = Db::name('arctype')->where($where)->group('parent_id')->cache(true, EYOUCMS_CACHE_TIME, 'arctype')->column('parent_id');
            $cookied_treeclicked =  json_decode(cookie('admin-treeLinkClicked-Arr'));
            empty($cookied_treeclicked) && $cookied_treeclicked = [];
            $all_treeclicked = cookie('admin-treeLinkClicked_All');
            empty($all_treeclicked) && $all_treeclicked = [];
            $tree = [
                'has_children'=>!empty($parent_ids) ? 1 : 0,
                'parent_ids'=>json_encode($parent_ids),
                'all_treeclicked'=>$all_treeclicked,
                'cookied_treeclicked'=>$cookied_treeclicked,
                'cookied_treeclicked_arr'=>json_encode($cookied_treeclicked),
            ];
            $assign_data['tree'] = $tree;
        }
        else {
            // 指定分组的链接列表
            $where = ['status'=>1];
            if ($this->php_servicemeal <= 20) {
                $where['link_id'] = ['NOTIN', [23]]; // 积分商城
            }
            $linkList = Db::name('ad_link')->where($where)->order('sort_order asc, link_id asc')->select();
            $assign_data['linkList'] = group_same_key($linkList, 'host_id');
        }

        $this->assign($assign_data);

        return $this->fetch('link');
    }
}